<?php
defined('BASEPATH') or exit('No direct script access allowed');

class Crons extends Backend
{

    public function __construct()
    {
        parent::__construct();
        $this->load->model(['job_model', 'category_model']);

        $this->data['jobtype'] = [
            "batchpush" => '批量推送',
            "pushall" => '筛选推送',
        ];
        $this->data['statustype'] = [
            "0" => '等待处理',
            "1" => '处理中',
            "2" => '任务完成',
            "3" => '任务失败',
            "4" => '任务取消',
            "5" => '每日上限',
        ];
        $this->data['statuslabel'] = [
            "0" => 'label-primary',
            "1" => 'label-info',
            "2" => 'label-success',
            "3" => 'label-danger',
            "4" => 'label-danger',
            "5" => 'label-warning',
        ];
        //
        $this->data['page_home'] = lang('lang_dashboard');
        $this->data['page_title'] = lang('lang_task');
    }


    public function index()
    {
        // Title
        $this->data['meta_title'] = $this->data['page_title'];

        // Breadcrumbs
        $this->data['array_breadcrumbs'] = array(
            $this->data['page_home'] => 'backend',
            $this->data['page_title'] => 'backend/task'
        );

        $page = max(1, (int)$this->input->get('page'));
        $key = trim($this->input->get('keyword'));
        $adminid = (int)$this->input->get('adminid');

        $page_data = $this->job_model->getpage($page, $key);
        $this->data['data'] = $page_data["data"];
        $this->data['pager'] = $page_data["pager"];


        $keyword = array(
            'name' => 'keyword',
            'id' => 'keyword',
            'value' => $key,
            'class' => 'form-control input-sm',
            'placeholder' => '请输入关键字',
            'maxlength' => '100'
        );
        $this->data['keyword'] = $keyword;

        //
        $this->data['content_header_title'] = content_header_title($this->data['page_title'], "列表");
        $this->data['content'] = 'task';

        //
        $this->render();
    }

    public function resetjob()
    {

        $return = ["status" => 1];
        $cid = $this->input->post("cid");
        $notice_data = array("status" => 0);

        if (!$this->job_model->update($cid, $notice_data)) {
            $return["status"] = 0;
            $return["msg"] = "重置失败";
        }

        echo json_encode($return);
        die();

    }

    public function ajaxlistcron()
    {
        exec("ps -Af|grep do_job|tr -s ' '", $output, $return);
        $count = 0;
        $returndata = ["data" => []];
        $rows = [];
        if ($output) {
            foreach ($output as $row) {
                if (strpos($row, 'index.php') !== false) {
                    $count++;
                    $row = explode(' ', $row);
                    $rows[] = ["count" => $count, "pid" => $row[1], "stime" => $row[4]];
                }
            }
        }
        $returndata["data"] = $rows;
        echo json_encode($returndata);
        die();
    }


    public function killcron()
    {
        $pid = $this->input->post["pid"];
        exec("sudo kill " . $pid);
        echo json_encode(["ok" => 1]);
        die("");
    }

    public function summary()
    {
        $catid = $this->input->post["catid"];
        exec("/usr/bin/php /www/wwwroot/everevive.com/index.php tool summarycate " . $catid);
        echo json_encode(["ok" => 1]);
        die("");
    }

    public function immediately_do_job()
    {
        exec("/usr/bin/php /www/wwwroot/ss/index.php cron do_job", $output, $result_code);
        $return["status"] = 1;
        if (strstr(implode($output), 'no job')) {
            $return["msg"] = '当前没有任务';
        } elseif (strstr(implode($output), 'exist')) {
            $return["msg"] = '推送商品已存在';
        } elseif (strstr(implode($output), 'prid')) {
            $return["msg"] = '推送产品重复，请检查采集产品';
        } else {
            $return["msg"] = implode($output);
        }
        echo json_encode($return);
        die();
    }

    public function canceljob()
    {

        $return = ["status" => 1];
        $cid = $this->input->post("cid");
        $notice_data = array("status" => 4);

        if (!$this->job_model->update($cid, $notice_data)) {
            $return["status"] = 0;
            $return["msg"] = "取消失败";
        }

        echo json_encode($return);
        die();

    }

    public function ajaxadd()
    {
        $catid = $this->input->post("catid");
        $siteid = $this->input->post("siteid");
        $limits = intval($this->input->post("limits"));
        $startindex = intval($this->input->post("startindex"));

        if (empty($groupnum)) $groupnum = 0;

        $query = $this->input->post("filter");
        $this->load->model(['goods_model', 'site_model', 'sitecategory_model']);

        if (strstr($query, "?")) {
            $tmp = explode("?", $query);
            $gcatid = $tmp[0];
            $url = $tmp[1];
            parse_str($url, $filter);
            foreach ($filter as $k => $f) {
                if (empty($f)) {
                    unset($filter[$k]);
                }
            }
            $filter["gcatid"] = $gcatid;
        } else {
            $gcatid = $query;
            $filter = ["gcatid" => $gcatid];
        }

        $cat = $this->category_model->getitembyid($filter["gcatid"]);
        $filter["startindex"] = $startindex;
        $filter["limits"] = $limits;
        $total = $this->goods_model->getfiltercount($filter);
        if ($total <= 0) {
            echo json_encode(["status" => 0, "msg" => "产品不能为空"]);
            die();
        }

        $filter["siteid"] = $siteid;
        $filter["catid"] = $catid;

        $newdata = [
            "job_type" => "pushall",
            "totals" => $total,
            "filter" => json_encode($filter),
        ];
        $site = $this->site_model->getitembyid($siteid);
        $sitecategory = $this->sitecategory_model->getitembyid($catid);
        $newdata["note"] = "按条件推送所有，产品库 <a href='/backend/products/pagelist/" . $filter["gcatid"] . "' target='_blank'>" . $cat["name"] . "</a>，推送店铺 <a href='/backend/sites/category/index/" . $siteid . "' target='_blank'>" . $site["name"] . "</a>,推送分类:" . $sitecategory["name"];
        $this->job_model->create($newdata);

        echo json_encode(["status" => 1]);
        die();
    }
}
